package show.me.the.money.service.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;

import show.me.the.money.accredit.DatabaseUserLoader;
import show.me.the.money.accredit.Organization;
import show.me.the.money.accredit.UsersController;
import show.me.the.money.util.MD5StringUtil;
import show.me.the.money.util.context.Context;


@SuppressWarnings("unchecked")
public class RoleLocator implements Service {

	@Override
	public void execute(HashMap<String, Object> req,
			HashMap<String, Object> res, Context ctx) {
		String uid = (String)req.get("uid");
		String psw = MD5StringUtil.MD5Encode((String)req.get("psw"));
		if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(psw)){
			res.put(Service.RES_CODE, 405);
			res.put(Service.RES_MESSAGE, "password emtry");
			return;
		}
		Document doc = UsersController.instance().getConfigDoc(uid);
		if(doc == null){
			doc = DatabaseUserLoader.getUserDoc(uid);
		}
		if(doc == null){
			res.put(Service.RES_CODE, 406);
			res.put(Service.RES_MESSAGE, "user not found");
			return;
		}
		Element root = doc.getRootElement();
		String password = root.attributeValue("password","");
		if(psw.equals(password)){
			List<Element> roles = root.selectNodes("roles/role");
			List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
			for(Element rel : roles){
				HashMap<String, Object> body = new HashMap<String, Object>();
				String r_uid = rel.attributeValue("id");
				if(r_uid != null){
					Element el = Organization.instance().getRoleElementById(r_uid);
					if(el != null){
						body.put("key", el.attributeValue("id"));
						body.put("text", el.attributeValue("name"));
						list.add(body);
					}
				}
			}
			res.put(Service.RES_CODE, 200);
			res.put(Service.RES_MESSAGE, "sucess");
			res.put("body", list);
		}else{
			res.put(Service.RES_CODE, 408);
			res.put(Service.RES_MESSAGE, "password error");
		}
		

	}

}
